﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;

namespace Paltop_v0._1.UI
{
    public partial class UploadEngine : System.Web.UI.Page
    {
        #region Web Methods
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.IsPostBack)
                {
                    UploadDetail Upload = (UploadDetail)this.Session["UploadDetail"];
                    //Let the webservie know that we are not yet ready
                    Upload.IsReady = false;

                    if (this.fileUploader.PostedFile != null && this.fileUploader.PostedFile.ContentLength > 0)
                    {
                        //build the local path where upload all the files
                        string path = Server.MapPath("\\" + Session["UPLOADFOLDER"].ToString());
                        
                        string fileName = Path.GetFileName(this.fileUploader.PostedFile.FileName);

                        //Build the strucutre and stuff it into session
                        Upload.ContentLength = this.fileUploader.PostedFile.ContentLength;
                        Upload.FileName = fileName;
                        Upload.UploadedLength = 0;
                        //Let the polling process know that we are done initializing ...
                        Upload.IsReady = true;

                        //set the buffer size to something larger.
                        //the smaller the buffer the longer it will take to download, 
                        //but the more precise your progress bar will be.
                        int bufferSize = 1;
                        byte[] buffer = new byte[bufferSize];
                          var temp = Session["ACCOUNTID"];
                        String title=fileName;
                        String ExtentionTiltle=fileName;
                        if (ExtentionTiltle.Contains('.'))
                            ExtentionTiltle = ExtentionTiltle.Substring(ExtentionTiltle.LastIndexOf('.')+1);
                        else
                            ExtentionTiltle = "unknown";
                        int parentId=0;
                        if (Session["FILEIDUPLOAD"] != null)
                        {
                            parentId = Convert.ToInt32(Session["FILEIDUPLOAD"].ToString());
                        }

                        //Writing the byte to disk
                        using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
                        {
                            
                            //Aslong was we haven't written everything ...
                            while (Upload.UploadedLength < Upload.ContentLength)
                            {
                                //Fill the buffer from the input stream
                                int bytes = this.fileUploader.PostedFile.InputStream.Read(buffer, 0, bufferSize);
                                //Writing the bytes to the file stream
                                fs.Write(buffer, 0, bytes);
                                //Update the number the webservice is polling on to the session
                                Upload.UploadedLength += bytes;
                            }
                        }
                        //Call parent page know we have processed the uplaod
                        const string js = "window.parent.onComplete(1,'File uploaded successfully.','{0}','{1} of {2} Bytes');";
                        Paltop_.Controllers.FileManagerController f = new Paltop_.Controllers.FileManagerController();
                      
                        int size = Upload.ContentLength;

                        int accountId=0;
                        if (temp != null)
                        {
                            accountId = Convert.ToInt32(temp);

                        }
                        f.AddFile(accountId, title, ExtentionTiltle, parentId, size);
                        ScriptManager.RegisterStartupScript(this, typeof(UploadEngine), "progress", string.Format(js, fileName, Upload.UploadedLength, Upload.ContentLength), true);
                    }
                    else
                    {
                        //Call parent page know we have processed the uplaod
                        const string js = "window.parent.onComplete(4, 'There was a problem with the file.','','0 of 0 Bytes');";
                        ScriptManager.RegisterStartupScript(this, typeof(UploadEngine), "progress", js, true);
                    }
                    //Let webservie know that we are not yet ready
                    Upload.IsReady = false;
                }
            }
            catch (Exception ex)
            {

                //what shal I do ?!! :D
            }
        }
        #endregion
    }

}
